import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryOrderDeliver, queryOrderGoods, queryRule, queryStore, requestRefund} from './service';
import Access from '@/components/Access/Access';
import {Select, Tag, Modal, Button, message, Table} from "antd";

const TableList = (props) => {

  const extraParams = {
    type: 3,
    subType: 5,
  };

  const [loading, setLoading] = useState(false);

  const actionRef = useRef();
  const [count, setCount] = useState();
  const [storeArr , setStoreArr] = useState([]);
  const [refundVisible, setRefundVisible] = useState(false); // 是否展示审核弹框
  const [currentRecord , setCurrentRecord] = useState({}); // 当前选定订单

  const handleGetStore = async () => {
    const {data} = await queryStore();
    setStoreArr(data);
  };
  useEffect(() => {
    handleGetStore();
  }, []);

  // 审核退款 flag: 通过/不通过
  const handleRefund  = (flag) => {
    setLoading(true);
    console.log("审核退款", flag)
    requestRefund({actOrderId: currentRecord.id, yesOrNo: flag}).then((res) => {
      if (!res) {
        console.log('响应失败');
        message.error('操作失败');
        return;
      }
      if (res.code === 0) {
        message.success('操作成功');
        clearCurrent();
        actionRef.current.reload();
      }else {
        message.error(res.message ? res.message : '操作失败');
        clearCurrent();
      }
    }).finally(() => setLoading(false));
  };

  // 退款弹框关闭
  const cancelRefund = () => {
    clearCurrent();
    message.info('已取消');
  }

  const clearCurrent = () => {
    setCurrentRecord({});
    setRefundVisible(false);
    setActivityGoodsVisible(false);
    setCurrentOrderGoods([]);
    setOrderDeliverVisible(false);
    setCurrentOrderDeliver([]);
  };

  const statusEnum = {
    '0': {status: 0, name: '正常', color: 'processing'},
    '1': {status: 1, name: '退单审核中', color: 'error'},
    '2': {status: 2, name: '已退单', color: 'warning'},
    '3': {status: 3, name: '退单被拒(正常)', color: 'processing'},
    '4': {status: 4, name: '取消退单(正常)', color: 'processing'},
    '999': {status: 999, name: '已完成', color: 'success'},
  };

  // 订单列定义
  const columns = [
    {
      title: '套餐名',
      dataIndex: 'activityName',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '下单店铺',
      dataIndex: 'storeId',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择下单店铺"
            showSearch
            filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            allowClear
          >
            {storeArr.map((item_, index) => {
              return (
                <Select.Option key={index} value={item_.id}>
                  {item_.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '下单店铺',
      dataIndex: 'storeName',
      hideInSearch: true,
    },
    {
      title: '会员名',
      dataIndex: 'memberName',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      hideInTable: true,
    },
    {
      title: '售价',
      dataIndex: 'activityFull',
      valueType: 'money',
      hideInSearch: true,
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      valueType: 'dateTime',
      sorter: (a, b) => a.createTime - b.createTime,
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.createTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },
    {
      title: '配送周期(月)',
      dataIndex: 'activityDelivTimeType',
      valueType: 'number',
      hideInSearch: true,
    },
    {
      title: '总期数',
      dataIndex: 'activityDelivCount',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (dom, entity) => {
        return (
          <Tag color={statusEnum[entity.status.toString()].color}>
            {statusEnum[entity.status.toString()].name}
          </Tag>
        )
      },
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder={'状态'}
            allowClear
          >
            {Object.values(statusEnum).map(item => {
                return (
                  <Select.Option key={item.status} value={item.status}>{item.name}</Select.Option>
                );
            })}
          </Select>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Button type="default" size="small"
                  style={{color: 'green'}}
                  loading={loading}
                  onClick={() => loadOrderGoodsData(record)}
          >
            套餐商品
          </Button>
          &nbsp;
          <Button type="default" size="small"
                  style={{color: 'green'}}
                  loading={loading}
                  onClick={() => loadOrderDeliver(record)}
          >
            配送记录
          </Button>
          &nbsp;
          <Access accessKey={"@refundPackageActivityOrder"}>
            {
              record.status === statusEnum['1'].status ?
                <Button type="primary" danger size="small"
                        loading={loading}
                        onClick={() => {
                          setCurrentRecord(record);
                          setRefundVisible(true);
                        }}
                >
                  退单审核
                </Button>
                : <></>
            }
          </Access>
        </>

      ),
    },
  ];

  // 商品相关
  const [activityGoodsVisible, setActivityGoodsVisible] = useState(false);
  const [currentOrderGoods, setCurrentOrderGoods] = useState([]); // 当前选定订单的商品
  // 加载商品数据
  const loadOrderGoodsData = (record) => {
    setCurrentRecord(record);
    setLoading(true);
    setActivityGoodsVisible(true);
    // 查询订单商品
    queryOrderGoods({activityOrderId: record.id}).then((res) => {
      if (!res) {
        message.error('操作失败');
        clearCurrent();
        return;
      }
      if (res.code === 0) {
        console.log(res)
        res.data.forEach((item, index) => item.key = item.id);
        setCurrentOrderGoods(res.data);
      }else {
        message.error(res.message ? res.message : '加载失败');
        clearCurrent();
      }
    }).finally(() => setLoading(false));
  };
  // 商品列定义
  const orderGoodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '数量',
      dataIndex: 'count',
      render: (dom, entity) => {
        return (<>X {entity.count} {entity.goodsUnit}</>)
      },
    },
  ];

  // 配送相关
  const [orderDeliverVisible, setOrderDeliverVisible] = useState(false);
  const [currentOrderDeliver, setCurrentOrderDeliver] = useState([]);
  const loadOrderDeliver = (record) => { // 加载配送记录
    setCurrentRecord(record);
    setLoading(true);
    setOrderDeliverVisible(true);
    // 查询订单商品
    queryOrderDeliver({activityOrderId: record.id}).then((res) => {
      if (!res) {
        message.error('操作失败');
        clearCurrent();
        return;
      }
      if (res.code === 0) {
        console.log(res)
        res.data.forEach((item, index) => item.key = item.id);
        setCurrentOrderDeliver(res.data);
      }else {
        message.error(res.message ? res.message : '加载失败');
        clearCurrent();
      }
    }).finally(() => setLoading(false));
  };
  // 配送记录列定义
  const orderDeliverColumns = [
    {
      title: '配送时间',
      dataIndex: 'deliverTime',
      render: (dom, entity) => {
        return new Date(entity.deliverTime).toLocaleString();
      },
    },
    {
      title: '配送人',
      dataIndex: 'deliverName',
    },
  ];

  return (
    <PageContainer>
      {/*数据列表*/}
      <ProTable
        headerTitle="套餐活动订单"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1200}} bordered
        toolBarRender={() => []}
        request={(params, sorter, filter) =>
          queryRule({...params, sorter, filter, ...extraParams})
        }
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />

      {/*退单审核弹框*/}
      <Modal
        visible={refundVisible}
        title="退单审核"
        onCancel={cancelRefund}
        footer={[
          <Button key="cancel" loading={loading} onClick={cancelRefund}>取消</Button>,
          <Button key="reject"
                  danger type="primary"
                  loading={loading}
                  onClick={() => {
                    handleRefund(false)
                  }}
          >
            拒绝
          </Button>,
          <Button
            key="resole"
            type="primary"
            loading={loading}
            onClick={() => {
              handleRefund(true);
            }}
          >
            通过
          </Button>,
        ]}
      >
        <p>{'(' + currentRecord.memberName + ') ' + currentRecord.activityName}</p>
      </Modal>

      {/*套餐商品弹框*/}
      <Modal
        visible={activityGoodsVisible}
        title={'商品列表 ' + currentRecord.memberName + ' ' + currentRecord.activityName}
        onCancel={clearCurrent}
        footer={[
          <Button key="cancel" onClick={clearCurrent}>关闭</Button>,
        ]}
      >
        <Table
          columns={orderGoodsColumns}
          dataSource={currentOrderGoods}
          loading={loading}
          pagination={false}
        />
      </Modal>

      {/*配送记录弹框*/}
      <Modal
        visible={orderDeliverVisible}
        title={'配送记录 ' + currentRecord.memberName + ' ' + currentRecord.activityName}
        onCancel={clearCurrent}
        footer={[
          <Button key="cancel" onClick={clearCurrent}>关闭</Button>,
        ]}
      >
        <Table
          columns={orderDeliverColumns}
          dataSource={currentOrderDeliver}
          loading={loading}
          pagination={false}
        />
      </Modal>

    </PageContainer>
  );
};

export default TableList;
